package com.osslearn.utils;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.osslearn.properties.AliOssProperties;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.UUID;

@Slf4j
@Component
@RequiredArgsConstructor
public class OssUtils {

    private final AliOssProperties ossProperties;

    /**
     * 上传文件到OSS
     * @param file 上传的文件
     * @return 文件访问URL
     */
    public String uploadFile(MultipartFile file) throws IOException {
        return uploadFile(file.getBytes(), generateObjectName(file));
    }

    /**
     * 上传字节数组到OSS
     * @param bytes 文件字节数组
     * @param objectName OSS对象名称
     * @return 文件访问URL
     */
    public String uploadFile(byte[] bytes, String objectName) {
        // 创建OSSClient实例
        String endpoint = "https://"+ossProperties.getEndpoint();
        OSS ossClient = new OSSClientBuilder().build(
                endpoint,
                ossProperties.getAccessKeyId(),
                ossProperties.getAccessKeySecret()
        );

        try {
            // 创建PutObject请求
            ossClient.putObject(
                    ossProperties.getBucketName(),
                    objectName,
                    new ByteArrayInputStream(bytes)
            );

            // 生成文件访问URL
            String fileUrl = generateFileUrl(objectName);
            log.info("文件成功上传到: {}", fileUrl);
            return fileUrl;

        } catch (OSSException oe) {
            log.error("OSS异常: 错误消息={}, 错误码={}, 请求ID={}, 主机ID={}",
                    oe.getErrorMessage(), oe.getErrorCode(), oe.getRequestId(), oe.getHostId());
            throw new RuntimeException("OSS操作失败: " + oe.getErrorMessage(), oe);
        } catch (ClientException ce) {
            log.error("客户端异常: {}", ce.getMessage());
            throw new RuntimeException("OSS客户端错误: " + ce.getMessage(), ce);
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }

    /**
     * 生成唯一的对象名称
     * @param file 上传的文件
     * @return 格式化的对象名称 (如: "uploads/2023/08/9a7d8f6a-5b3c-4e.jpg")
     */
    private String generateObjectName(MultipartFile file) {
        String originalFilename = file.getOriginalFilename();
        String extension = originalFilename != null && originalFilename.contains(".")
                ? originalFilename.substring(originalFilename.lastIndexOf("."))
                : "";

        return String.format("uploads/%s/%s/%s%s",
                getCurrentYear(),
                getCurrentMonth(),
                UUID.randomUUID(),
                extension);
    }

    private String getCurrentYear() {
        return String.valueOf(java.time.Year.now().getValue());
    }

    private String getCurrentMonth() {
        return String.format("%02d", java.time.LocalDate.now().getMonthValue());
    }

    /**
     * 生成文件访问URL
     * @param objectName OSS对象名称
     * @return 完整的文件URL
     */
    private String generateFileUrl(String objectName) {
        return "https://" + ossProperties.getBucketName() +
                "." + ossProperties.getEndpoint() +
                "/" + objectName;
    }
}